package com.voole.wideget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.Button;
import com.facebook.rebound.BaseSpringSystem;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringSystem;
import com.facebook.rebound.SpringUtil;

public class VButton extends Button {

	private Spring mScaleSpring;
	private final BaseSpringSystem mSpringSystem = SpringSystem.create();
	private final ExampleSpringListener mSpringListener = new ExampleSpringListener();

	public VButton(Context context) {
		super(context);
		vInit();
	}

	public VButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		vInit();
	}

	public VButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		vInit();
	}

	private void vInit() {
		mScaleSpring = mSpringSystem.createSpring();
	}

	@Override
	protected void onFocusChanged(boolean focused, int direction,
			Rect previouslyFocusedRect) {
		super.onFocusChanged(focused, direction, previouslyFocusedRect);
		if (focused) {
			mScaleSpring.setEndValue(1);
			bringToFront();
		} else {
			mScaleSpring.setEndValue(0);
			
		}
	}

	@SuppressLint("NewApi")
	private void onScale(float x, float y) {
		setScaleX(x);
		setScaleY(y);
	}
	
	@Override
	public void setSelected(boolean selected) {
		super.setSelected(selected);
		if (selected) {
			mScaleSpring.setEndValue(1);
			bringToFront();
		} else {
			mScaleSpring.setEndValue(0);
			
		}
		
	}
	
	@Override
	public void setPressed(boolean pressed) {
		super.setPressed(pressed);
		if(mScaleSpring!=null){
			if (pressed) {
				mScaleSpring.setEndValue(1);
				bringToFront();
			} else {
				mScaleSpring.setEndValue(0);
			}
			}
	}
	

	@Override
	protected void onDetachedFromWindow() {
		mScaleSpring.removeListener(mSpringListener);
		super.onDetachedFromWindow();
	}
	
	@Override
	protected void onAttachedToWindow() {
		mScaleSpring.addListener(mSpringListener);
		super.onAttachedToWindow();
	}

	private class ExampleSpringListener extends SimpleSpringListener {
		@Override
		public void onSpringUpdate(Spring spring) {
			float mappedValue = (float) SpringUtil.mapValueFromRangeToRange(
					spring.getCurrentValue(), 0, 1, 1, 2);onScale(mappedValue, mappedValue);
		}
	}

}
